package org.example.Handler;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.example.Command.CommonMessage;
import org.example.Command.ShowMessage;
import org.example.Entity.FileFactory;
import org.example.Entity.MyFile;

import java.util.ArrayList;

import static org.example.Poll.pipeline;
import static org.example.Utils.StringUtils.getIp;

public class ShowCommandServerHandler extends SimpleChannelInboundHandler<ShowMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ShowMessage msg) throws Exception {
        System.out.println(msg);
        //存储ip下的所有文件
        ArrayList<MyFile> myFiles = new ArrayList<>();
        String ip = getIp(ctx.channel().remoteAddress());
        Integer sequenceId = msg.getSequenceId();
        //提取该ip下的所有文件
        pipeline.forEach((key, fileRes) -> {
            if (fileRes.getIp().equals(ip)) {
                myFiles.add(fileRes);
            }
        });
        if (myFiles.isEmpty()) {
            ctx.writeAndFlush(new CommonMessage("空", sequenceId));
        }
        myFiles.forEach(file -> {
            if (msg.getShowAll()) {
                ctx.writeAndFlush(new CommonMessage(file.toString(), sequenceId));
            } else {
                if (file.getCounts() > 0 && !FileFactory.isExpired(file)) {
                    ctx.writeAndFlush(new CommonMessage(file.toString(), sequenceId));
                }
            }
        });
        ctx.writeAndFlush(CommonMessage.getEnd(sequenceId));
    }
}
